<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreatedAt"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="版本号" prop="version">
        <el-input
          v-model="queryParams.version"
          placeholder="请输入版本号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ota:ota:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ota:ota:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ota:ota:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ota:ota:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="otaList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" width="50" label="序号" align="center" />
      
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="版本号" align="center" prop="version" />
      <el-table-column label="版本文件" align="center" prop="filePath" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ota:ota:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ota:ota:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看OTA版本详情对话框 -->
    <el-dialog :title="viewTitle" :visible.sync="viewOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="版本号">{{ viewForm.version }}</el-descriptions-item>
        <el-descriptions-item label="版本文件">{{ viewForm.filePath }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">
          {{ parseTime(viewForm.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}
        </el-descriptions-item>
      </el-descriptions>
      
      <el-divider content-position="center">OTA分割信息</el-divider>
      <el-table :data="viewOtaSplitList" :row-class-name="rowViewOtaSplitIndex" border>
        
        <el-table-column label="文件序列号" prop="seqNum" width="150" align="center" />
        <el-table-column label="片段长度" prop="length" width="150" align="center" />
        <el-table-column label="数据内容" prop="data" align="center">
          <template slot-scope="scope">
            <div 
              class="data-content"
              @mouseover="showFullData(scope.row, $event)"
              @mouseout="hideFullData"
            >
              {{ scope.row.data ? (scope.row.data.length > 50 ? scope.row.data.substring(0, 50) + '...' : scope.row.data) : '-' }}
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 添加或修改OTA版本对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="版本号" prop="version">
          <el-input v-model="form.version" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="版本文件" prop="filePath">
          <file-upload v-model="form.filePath"/>
        </el-form-item>                 
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOta, getOta, delOta, addOta, updateOta } from "@/api/ota/ota"

export default {
  name: "Ota",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedOtaSplit: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // OTA版本表格数据
      otaList: [],
      // OTA分割表格数据
      otaSplitList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // OTA片段时间范围
      daterangeCreatedAt: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        filePath: null,
        createdAt: null,
        version: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        filePath: [
          { required: true, message: "版本文件不能为空", trigger: "blur" }
        ],
        createdAt: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        version: [
          { required: true, message: "版本号不能为空", trigger: "blur" }
        ]
      },
      // 查看相关数据
      viewOpen: false,
      viewTitle: "查看OTA版本详情",
      viewForm: {},
      viewOtaSplitList: [],
      tooltipVisible: false,
      tooltipContent: ""
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询OTA版本列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeCreatedAt && '' != this.daterangeCreatedAt) {
        this.queryParams.params["beginCreatedAt"] = this.daterangeCreatedAt[0]
        this.queryParams.params["endCreatedAt"] = this.daterangeCreatedAt[1]
      }
      listOta(this.queryParams).then(response => {
        this.otaList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        filePath: null,
        createdAt: null,
        version: null
      }
      this.otaSplitList = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreatedAt = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加OTA版本"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getOta(id).then(response => {
        this.form = response.data
        this.otaSplitList = response.data.otaSplitList
        this.open = true
        this.title = "修改OTA版本"
      })
    },
    /** 查看按钮操作 */
    handleView(row) {
      const id = row.id
      getOta(id).then(response => {
        this.viewForm = response.data
        this.viewOtaSplitList = response.data.otaSplitList || []
        this.viewOpen = true
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.otaSplitList = this.otaSplitList
          if (this.form.id != null) {
            updateOta(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addOta(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除OTA版本编号为"' + ids + '"的数据项？').then(function() {
        return delOta(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
	/** OTA分割序号 */
    rowOtaSplitIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 查看弹窗OTA分割序号 */
    rowViewOtaSplitIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** OTA分割添加按钮操作 */
    handleAddOtaSplit() {
      let obj = {}
      obj.seqNum = ""
      obj.length = ""
      obj.data = ""
      this.otaSplitList.push(obj)
    },
    /** OTA分割删除按钮操作 */
    handleDeleteOtaSplit() {
      if (this.checkedOtaSplit.length == 0) {
        this.$modal.msgError("请先选择要删除的OTA分割数据")
      } else {
        const otaSplitList = this.otaSplitList
        const checkedOtaSplit = this.checkedOtaSplit
        this.otaSplitList = otaSplitList.filter(function(item) {
          return checkedOtaSplit.indexOf(item.index) == -1
        })
      }
    },
    /** 复选框选中数据 */
    handleOtaSplitSelectionChange(selection) {
      this.checkedOtaSplit = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ota/ota/export', {
        ...this.queryParams
      }, `ota_${new Date().getTime()}.xlsx`)
    },
    /** 显示完整数据 */
    showFullData(row, event) {
      if (row.data && row.data.length > 50) {
        this.tooltipContent = row.data
        this.tooltipVisible = true
      }
    },
    /** 隐藏完整数据 */
    hideFullData() {
      this.tooltipVisible = false
    }
  }
}
</script>

<style scoped>
.data-content {
  cursor: pointer;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tooltip-trigger {
  position: fixed;
  top: -100px;
  left: -100px;
  width: 1px;
  height: 1px;
  opacity: 0;
  pointer-events: none;
}

/* 自定义tooltip样式 */
:deep(.data-tooltip) {
  max-width: 400px;
  word-break: break-all;
  white-space: pre-wrap;
  line-height: 1.5;
  background-color: #303133;
  color: #fff;
  border: 1px solid #303133;
  border-radius: 4px;
  padding: 8px 12px;
  font-size: 12px;
}
</style>
